<script setup >
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ'
import TileLayer from 'ol/layer/Tile';
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox  } from 'element-plus'
import SnowflakeId from "snowflake-id"
import {fromLonLat, toLonLat} from "ol/proj";
import proj4 from 'proj4';
import { register } from 'ol/proj/proj4';
import { transform } from 'ol/proj';
import {wgs84togcj02} from 'coordtransform';

// 注册proj4定义
proj4.defs("EPSG:3857","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs");
proj4.defs("EPSG:4326","+proj=longlat +datum=WGS84 +no_defs");

register(proj4);

const managerMap = ref({})
const mapUrl = ref(`tiles/{z}/{x}/{y}.png`)

const dialogVisible = ref(false)

const formInline = ref({
  name: '',
})

const editForm = ref({
  id: "",
  name: "",
  owner: "",
  phone: "",
  address: "",
  documentImage: ["",""],
  level: "",
  checkPerson: [],
  position: ["",""],
})


function initMap() {

  managerMap.value = new Map({
    layers: [
      new TileLayer({
        source: new XYZ({
          url: mapUrl.value
        })
      }),
    ],
    view: new View({
      center: fromLonLat([118.886373,39.432084]), // 地图中心点
      zoom: 15, // 初始缩放级别
      minZoom: 10, // 最小缩放级别
      maxZoom: 18 // 最大缩放级别
    }),
    target: 'manager-map'
  });

  // 添加点击事件监听器
  managerMap.value.on('click', function(event) {
    // 获取点击位置的像素坐标
    const pixel = event.pixel;
    // 将像素坐标转换为地理坐标
    const coordinate = managerMap.value.getCoordinateFromPixel(pixel);
    const lonLat = toLonLat(coordinate);

    editForm.value.position[0] = lonLat[0]+"";
    editForm.value.position[1] = lonLat[1]+"";
  });
}

function submitSearch() {
  loadData();
}

async function submitForm() {
  if(editForm.value.id !== ''){
    submitModify();
  } else {
    submitAdd();
  }
}

async function submitAdd() {
  try{
    let dataList = await loadAllData();
    editForm.value.id = new SnowflakeId().generate();
    dataList.push(editForm.value);
    let content = JSON.stringify(dataList)
    await window.api.writeJsonFile("shop.json", content);
    dialogVisible.value = false;
    loadData();
  }catch (e){
    console.log(e);
    ElMessage.error('保存失败！')
    editForm.value.id = '';
  }

}

async function submitModify() {
  try{
    let dataList = await loadAllData();

    let index = -1;
    for(let i=0;i<dataList.length;i++) {
      let item = dataList[i];
      if(item.id === editForm.value.id){
        index = i;
        break;
      }
    }
    console.log(index);
    if(index === -1){
      ElMessage.error('未找到原始数据！');
      return ;
    }

    dataList.splice(index, 1, editForm.value);

    let content = JSON.stringify(dataList);
    await window.api.writeJsonFile("shop.json", content);
    dialogVisible.value = false;
    loadData();
  }catch(e) {
    ElMessage.error('保存失败！')
    console.log(e);
  }
}

function confirmToDelete(row) {

  ElMessageBox.confirm('确定删除吗?')
      .then(() => {
        doDelete(row)
      })
      .catch(() => {

      })
}

async function doDelete(row){

  try{
    let dataList = await loadAllData();

    let index = -1;
    for(let i=0;i<dataList.length;i++) {
      let item = dataList[i];
      if(item.id === row.id){
        index = i;
        break;
      }
    }
    console.log(index);
    if(index === -1){
      ElMessage.error('未找到原始数据！');
      return ;
    }

    dataList.splice(index, 1);

    let content = JSON.stringify(dataList);
    await window.api.writeJsonFile("shop.json", content);
    dialogVisible.value = false;
    loadData();
  }catch(e) {
    ElMessage.error('保存失败！')
    console.log(e);
  }
}

const openAdd = () => {
  dialogVisible.value = true;
  editForm.value = {
    id: "",
    name: "",
    owner: "",
    phone: "",
    address: "",
    documentImage: ["",""],
    level: "A",
    checkPerson: ["",""],
    position: ["",""],
  };
  initMap();
}

const tableData = ref([])

async function loadData(){
  try {
    let fileContent = await window.api.readJsonFile("shop.json");
    let list = JSON.parse(fileContent);
    if(typeof formInline.value.name !== "undefined" && formInline.value.name !== null && formInline.value.name !== ''){
      list = list.filter( (item) =>{
        return item.name.indexOf(formInline.value.name) !== -1
      } );
    }
    tableData.value = list;
  } catch (e) {
    ElMessage.error('数据文件不存在')
    tableData.value = [];
  }
}

async function loadAllData(){
  try {
    let fileContent = await window.api.readJsonFile("shop.json");
    return JSON.parse(fileContent);
  } catch (e) {
    return [];
  }
}




function openModify(row){
  dialogVisible.value = true;
  editForm.value = row;
}

function uploadImage(inputId, index){

  let input = document.getElementById(inputId);
  input.addEventListener('change', function(event) {
    const fileInput = event.target;
    const file = fileInput.files[0];

    if (!file) {
      return;
    }

    const reader = new FileReader();

    reader.onload = function(e) {
      console.log(e.target.result)
      if(inputId.startsWith("documentImage")){
        editForm.value.documentImage[index] = e.target.result;
      } else if(inputId.startsWith("checkPerson")){
        editForm.value.checkPerson[index] = e.target.result;
      }
    };

    reader.onerror = function() {

    };

    reader.readAsDataURL(file);
  });
  document.getElementById(inputId).click();
}


const userAndPwd = ref({
  userName: "admin",
  password: "admin@123?"
});

async function loadUserAndPwd(){
  try{
    let fileContent = await window.api.readJsonFile("pwd.json");
    let jsonObj = JSON.parse(fileContent);
    userAndPwd.value.userName = jsonObj.userName;
    userAndPwd.value.password = jsonObj.password;
  } catch (e){
    ElMessage.warning(e)
  }
}

const loginForm = ref({
  visible: true,
  userName: "",
  password: ""
});

function login(){
    if(loginForm.value.userName === userAndPwd.value.userName
        && loginForm.value.password === userAndPwd.value.password ){
      loginForm.value.visible = false;
    } else {
      ElMessage.error("用户名密码错误");
    }
}

const changePwdForm = ref({
  visible: false,
  userName: "",
  oldPassword: "",
  password: ""
});

async function changePwd(){
  if(changePwdForm.value.userName === userAndPwd.value.userName
      && changePwdForm.value.oldPassword === userAndPwd.value.password ){
    userAndPwd.value = {
      userName: changePwdForm.value.userName,
      password: changePwdForm.value.password
    };
    let content = JSON.stringify({
      userName: changePwdForm.value.userName,
      password: changePwdForm.value.password
    })
    await window.api.writeJsonFile("pwd.json", content);
    changePwdForm.value.visible = false;
    loginForm.value.visible = true;

  } else {
    ElMessage.error("用户名密码错误");
  }
}

function showChangePwdDialog(){
  loginForm.value.visible = false;
  changePwdForm.value.visible = true;
}

function dialogOpened(){
  initMap();
}

onMounted(()=>{
  loadData();
  loadUserAndPwd();

})
</script>

<template>
  <el-container class="page-body">

    <el-dialog v-model="loginForm.visible" title="请登录管理员账户"
        width="500" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
    >
      <div>
        <el-form label-width="auto" style="max-width: 600px">
          <el-form-item label="账户">
            <el-input v-model="loginForm.userName" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input type="password" v-model="loginForm.password" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="login"> 登录 </el-button>
          <el-button type="primary" @click="showChangePwdDialog"> 修改密码 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="changePwdForm.visible" title="请登录管理员账户"
               width="500" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false"
    >
      <div>
        <el-form label-width="auto" style="max-width: 600px">
          <el-form-item label="账户">
            <el-input v-model="changePwdForm.userName" />
          </el-form-item>
          <el-form-item label="原始密码">
            <el-input type="password" v-model="changePwdForm.oldPassword" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input type="password" v-model="changePwdForm.password" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="changePwd"> 修改密码 </el-button>
        </div>
      </template>
    </el-dialog>

      <el-main style="width: 90%; height: 100vh;">
        <el-card>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="商户名称">
              <el-input v-model="formInline.name" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitSearch">查询</el-button>
            </el-form-item>
          </el-form>

          <div style="margin: 10px;">
            <el-button type="primary" @click="openAdd">新建</el-button>
          </div>

          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="id" label="系统编号"  />
            <el-table-column prop="name" label="商户名"  />
            <el-table-column prop="owner" label="业主"   />
            <el-table-column prop="phone" label="联系方式" />
            <el-table-column prop="address" label="店铺地址" />
            <el-table-column prop="level" label="信用等级" />
            <el-table-column label="操作" >
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <el-button type="primary" @click="openModify(scope.row)">修改</el-button>
                  <el-button type="primary" @click="confirmToDelete(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>

          </el-table>
        </el-card>
      </el-main>
  </el-container>

  <el-dialog v-model="dialogVisible" title="添加商户" width="700" @opened="dialogOpened" :destroy-on-close="true">
    <el-form :model="editForm" label-position="right" label-width="auto">
      <el-form-item style="display: none;" >
        <el-input v-model="editForm.id" />
      </el-form-item>

      <el-form-item label="商户名"  >
        <el-input v-model="editForm.name" />
      </el-form-item>

      <el-form-item label="经营者" >
        <el-input v-model="editForm.owner" />
      </el-form-item>

      <el-form-item label="联系方式"  >
        <el-input v-model="editForm.phone" />
      </el-form-item>

      <el-form-item label="地址"  >
        <el-input v-model="editForm.address" />
      </el-form-item>

      <el-form-item label="证件信息"  >
        <el-image style="width: 100px; height: 100px" fit="fill"
                  :src="editForm.documentImage[0]"
                  @click="uploadImage('documentImage0',0)"/>
        <input type="file" id="documentImage0" style="display: none;">
        <el-image style="width: 100px; height: 100px" fit="fill"
                  :src="editForm.documentImage[1]"
                  @click="uploadImage('documentImage1',1)"/>
        <input type="file" id="documentImage1" style="display: none;">
      </el-form-item>

      <el-form-item label="信用等级"  >
        <el-select v-model="editForm.level" size="large" style="width: 240px" >
          <el-option key="A" label="A" value="A" />
          <el-option key="B" label="B" value="B" />
          <el-option key="C" label="C" value="C" />
          <el-option key="D" label="D" value="D" />
        </el-select>
      </el-form-item>

      <el-form-item label="监管人员"  >
        <el-image style="width: 100px; height: 100px" :src="editForm.checkPerson[0]" @click="uploadImage('checkPerson0',0)"/>
        <input type="file" id="checkPerson0" style="display: none;">
        <el-image style="width: 100px; height: 100px" :src="editForm.checkPerson[1]" @click="uploadImage('checkPerson1',1)"/>
        <input type="file" id="checkPerson1" style="display: none;">
      </el-form-item>

      <el-form-item label="经度" >
        <el-input v-model="editForm.position[0]" />
      </el-form-item>

      <el-form-item label="维度"  >
        <el-input v-model="editForm.position[1]" />
      </el-form-item>

      <el-form-item>
        <div id="manager-map" style="width: 650px;height: 400px;margin: 0 auto;"/>
      </el-form-item>


    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitForm"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
  .page-body {
    width: 100%;
  }

  .el-header {
    padding: 0;
  }

  .page-header {
    background-color: black;
    color: whitesmoke;
    font-size: large;
    font-weight: bold;
    height: 60px;
    line-height: 60px;
    padding: 0 20px;
  }
</style>
